//
//  XLAnchorCommitInforVC.m
//  XiangLove
//
//  Created by 李传坤 on 2018/4/3.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLAnchorCommitInforVC.h"
#import "XLAnchorCommitHeaderCell.h"
#import "XLApplyInforModel.h"
#import "XLAccountManager.h"
#import "BMHPhotoPickManager.h"
#import "UIImage+Clip.h"
#import "BMHAreaPickView.h"
#import <ReactiveCocoa.h>
#import "BMHUserPickerView.h"
#import "XLEdNickViewController.h"
#import "XLHTTPSessionManager+TaskLevel.h"
#import "UIImage+Gradient.h"
#import "XLDownloadImageTool.h"
#import "XLHostApplyButtonCell.h"
#import "XLVideoPushFinishView.h"
#import "XLLLoginView.h"
#import "XLLLoginViewModel.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import "VideoRecordViewController.h"
#import <SVProgressHUD.h>
#import "XLSubmitUserInfoView.h"
#import "XLCommitDataController.h"
#import "SHShortVideoViewController.h"

@interface XLAnchorCommitInforVC ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, XLAnchorCommitHeaderCellDelagate,XLHostApplyButtonCellDelagate,XLSubmitUserInfoViewDelegate>{
    UITextField *GonghuiText;
}
@property (nonatomic, strong) UITableView        *tableView;
@property (nonatomic, strong) UIButton        *videoImageButton;
@property (nonatomic, strong) UILabel        *videolabel;
@property (nonatomic, strong) NSArray            *dataArray;
@property (nonatomic, strong) XLApplyInforModel  *userApplyModel;
@property (nonatomic, strong) XLLLoginView *loginView;
@property (nonatomic,   copy) NSString           *imageUrl;
@property (nonatomic,   copy) NSString           *coverImage;
@property (nonatomic,   copy) NSString           *videoUrl;
@property (nonatomic,   copy) NSString           *IDCardUrl1;
@property (nonatomic,   copy) NSString           *IDCardUrl2;
@property (nonatomic,   copy) NSString           *gonghuiID;

//弹窗容器
@property (nonatomic, strong) UIWindow *  window;

@end
@implementation XLAnchorCommitInforVC

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"commitVideoUpData" object:self];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    if (self.videoUrl.length == 0) {
        _videolabel.hidden = NO;
        [XLDownloadImageTool downloadImage:@"" place:[UIImage imageNamed:@"home_but_shangchuan_n"] button:_videoImageButton];
    }
}

#pragma mark    - - - 设置确认信息 - - -
- (void)setAlertWithPrompt
{
    //设置容器显示
    self.window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    self.window.backgroundColor = [UIColor clearColor];
    
    self.window.windowLevel = UIWindowLevelAlert + 1;
    
    //显示弹窗内容
    XLSubmitUserInfoView *userInfo = [[XLSubmitUserInfoView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    userInfo.delegate = self;
    
    [self.window addSubview:userInfo];
    
    [self.window makeKeyAndVisible];
}

#pragma mark    - - - XLSubmitUserInfoViewDelegate - - -

- (void)submitUserInfoViewSelectIndex:(NSInteger)index
{
    switch (index) {
        case 1:
            {
                //
                [self.window resignKeyWindow];
                self.window = nil;
            }
            break;
        case 2:{
            //跳转编辑资料页面
            
            [self.window resignKeyWindow];
            self.window = nil;
            
            XLCommitDataController *commitDataVc = [[XLCommitDataController alloc] init];
            
            [self.navigationController pushViewController:commitDataVc animated:YES];
            
            break;
        }
        case 3:{
            
            [self.window resignKeyWindow];
            self.window = nil;
            
            break;
        }
            
        default:
            
            [self.window resignKeyWindow];
            self.window = nil;
            
            break;
    }
}

- (instancetype)init {
    self = [super init];
    if (self) {
        if ([XLAccountManager shareInstance].loginViewModel) {
            self.viewModel = [XLAccountManager shareInstance].loginViewModel;
            self.viewModel.isHostApply = @"yes";
        } else {
            self.viewModel = [[XLLLoginViewModel alloc] init];
            self.viewModel.isHostApply = @"yes";
            [XLAccountManager shareInstance].loginViewModel = self.viewModel;
        }
    }
    return self;
}

-(void)commitVideoUpData:(NSNotification *)notification
{
    
    if ([notification.userInfo[@"key"] isKindOfClass:[NSString class]]) {
        NSString *loadPathStr = notification.userInfo[@"key"];
        self.videoUrl = loadPathStr;
    }else{
        UIImage *loadPathStr = notification.userInfo[@"key"];
        _videolabel.hidden = YES;
        [_videoImageButton setBackgroundImage:loadPathStr forState:UIControlStateNormal];
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //注册通知：
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(commitVideoUpData:) name:@"commitVideoUpData" object:nil];
    
    self.navigationItem.title = @"提交审核信息";
    [self showBackButton:NULL];
    self.dataArray = @[  @{@"title" : @"昵称",@"subTitle" : @"",@"indicator" : @(YES)},
                         @{@"title" : @"性别",@"subTitle" : @"",@"indicator" : @(YES)},
                         @{@"title" : @"年龄",@"subTitle" : @"",@"indicator" : @(YES)},
                         @{@"title" : @"地区",@"subTitle" : @"",@"indicator" : @(YES)},
                         @{@"title" : @"职业",@"subTitle" : @"",@"indicator" : @(YES)},
                         @{@"title" : @"工会ID",@"subTitle":@"",@"indicator" : @(YES)},
                    ];
    [self setupView];

    [[[XLHTTPSessionManager sharedManager] getGetAuditAnchorInfoWithUserId:[[XLAccountManager shareInstance] model].Id] subscribeNext:^(id x) {
        self.userApplyModel = x;
        [self setupData];
    }];
    
    //弹窗提示
    [self setAlertWithPrompt];
}

#pragma mark 提交
-(void)uploadApplyInforButton{
    if (self.imageUrl.length == 0) {
        [HelpTool startTipViewWithText:@"请上传头像" duration:2.0f type:kTipViewTypeNone];
        return;
    }
    if (self.videoUrl.length == 0) {
        [HelpTool startTipViewWithText:@"请上传视频" duration:2.0f type:kTipViewTypeNone];
        return;
    }
    if (self.IDCardUrl1.length == 0) {
        [HelpTool startTipViewWithText:@"请上传身份证正面" duration:2.0f type:kTipViewTypeNone];
        return;
    }
    if (self.IDCardUrl2.length == 0) {
        [HelpTool startTipViewWithText:@"请上传身份证反面" duration:2.0f type:kTipViewTypeNone];
        return;
    }
    if (self.loginView.codeField.text.length < 4 || self.loginView.phoneField.text.length < 11) {
        [HelpTool startTipViewWithText:@"手机号或验证码错误" duration:2.0f type:kTipViewTypeNone];
        return;
    }
    NSDictionary *dic = @{@"Photo"        :self.imageUrl,
                          @"Video"        :self.videoUrl,
                          @"Phone"        :self.loginView.phoneField.text,
                          @"IdCardForward":self.IDCardUrl1,
                          @"IdCardBack"   :self.IDCardUrl2,
                          @"MobileCode"   :self.loginView.codeField.text,
                          @"GuildCode"    :GonghuiText.text
                        };
    [[[XLHTTPSessionManager sharedManager] SubmitAnchorInfoWithUserId:[[XLAccountManager shareInstance] model].Id dic:dic] subscribeNext:^(id x) {
        //提交成功
        [self.navigationController popViewControllerAnimated:YES];
        [MBProgressHUD showContent:@"提交成功"];
        [XLAccountManager shareInstance].model.Status = @"-1";
    } error:^(NSError *error) {
        [MBProgressHUD showContent:[error.userInfo objectForKey:@"NSLocalizedDescription"]];
    }];
}
- (void)setupView {
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    GonghuiText = [[UITextField alloc]initWithFrame:CGRectMake(28, 4, 300, 44)];
    GonghuiText.delegate = self;
    GonghuiText.placeholder = @"请输入工会ID(选填)";
    GonghuiText.textColor = [UIColor darkGrayColor];
    GonghuiText.font = [UIFont systemFontOfSize:18];
    self.loginView = [[XLLLoginView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 140)];
    self.loginView.loginButton.hidden = YES;
    self.loginView.phoneField.textColor = kDarkGrayColor;
    self.loginView.phoneField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName : RGBA_HEX(0x000000, 0.3)}];
    self.loginView.codeField.textColor = kDarkGrayColor;
    self.loginView.codeField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入验证码" attributes:@{NSForegroundColorAttributeName : RGBA_HEX(0x000000, 0.3)}];
    [self bindingData];
}

- (void)setupData {
    self.imageUrl   = @"";
    self.coverImage   = @"";
    self.IDCardUrl1 = @"";self.IDCardUrl2 = @"";
    [self.tableView reloadData];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [GonghuiText resignFirstResponder];
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField == GonghuiText) {
        if (GonghuiText.text.length > 20) {
            GonghuiText.text = [GonghuiText.text substringToIndex:20];
        }
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    if (section == 1) {
        return 2;
    }
    if (section == 2) {
        return 1;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UITableViewCell class])];
    if (indexPath.section == 0) {
        XLAnchorCommitHeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLAnchorCommitHeaderCell class])];
        if (cell == nil) {
            cell = [[XLAnchorCommitHeaderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([XLAnchorCommitHeaderCell class])];
            cell.contentView.backgroundColor = XLThemeColor;
            cell.backgroundColor = XLThemeColor;
        }
        if (indexPath.row == 0) {//头像封面
            [XLDownloadImageTool downloadImage:self.imageUrl place:[UIImage imageNamed:@"home_but_shangchuan_n"] button:cell.headerImageview];
            if (_imageUrl.length > 0) {
                cell.headerLabel1.hidden = YES;
            }
            if (_videoUrl.length > 0) {
                cell.headerLabel2.hidden = YES;
            }
            [XLDownloadImageTool downloadImage:self.coverImage place:[UIImage imageNamed:@"home_but_shangchuan_n"] button:cell.coverImageview];
            cell.headerImageview.tag = 100;
            cell.coverImageview.tag = 101;
            cell.tittleLabel.text = @"上传真人照片和视频";
            cell.headerLabel1.text = @"上传真人照片";
            cell.headerLabel2.text = @"上传视频（10-15s）";
            cell.headerImageview.frame = CGRectMake(20, 50,SCREEN_WIDTH/2 - 30, SCREEN_WIDTH/2-30);
            cell.coverImageview.frame = CGRectMake(SCREEN_WIDTH/2 + 10, 50, SCREEN_WIDTH/2-30, SCREEN_WIDTH/2-30);
            _videoImageButton = cell.coverImageview;_videolabel =  cell.headerLabel2;
            [cell.headerLabel1 setFrame:CGRectMake(20, cell.contentView.frame.size.height-50,SCREEN_WIDTH/2-30, 35)];
            [cell.headerLabel2 setFrame:CGRectMake(SCREEN_WIDTH/2 + 10, cell.contentView.frame.size.height-50,SCREEN_WIDTH/2-30, 35)];
        }
        if (indexPath.row == 1) {//身份证
            [XLDownloadImageTool downloadImage:self.IDCardUrl1 place:[UIImage imageNamed:@"me_pic_sfz1"] button:cell.headerImageview];
            cell.headerLabel1.hidden = NO;
            [XLDownloadImageTool downloadImage:self.IDCardUrl2 place:[UIImage imageNamed:@"me_pic_sfz2_n"] button:cell.coverImageview];
            cell.headerLabel2.hidden = NO;
            cell.headerImageview.tag = 200;
            cell.coverImageview.tag = 201;
            cell.tittleLabel.text = @"上传身份证正反面";
            cell.headerLabel1.text = @"点击拍摄个人信息面";
            cell.headerLabel2.text = @"点击拍摄有效期面";
            cell.headerImageview.frame = CGRectMake(20, 50,SCREEN_WIDTH/2-30, SCREEN_WIDTH/3-20);
            cell.coverImageview.frame = CGRectMake(SCREEN_WIDTH/2 + 10, 50, SCREEN_WIDTH/2-30, SCREEN_WIDTH/3-20);
            cell.headerLabel1.backgroundColor = cell.headerLabel2.backgroundColor = [UIColor groupTableViewBackgroundColor];
            [cell.headerLabel1 setFrame:CGRectMake(20, SCREEN_WIDTH/3-20 + 50,SCREEN_WIDTH/2-30, 35)];
            [cell.headerLabel2 setFrame:CGRectMake(SCREEN_WIDTH/2 + 10, SCREEN_WIDTH/3-20 + 50,SCREEN_WIDTH/2-30, 35)];
            
        }
        cell.delagate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    } else if(indexPath.section == 1) {
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:NSStringFromClass([UITableViewCell class])];
        }
        if (indexPath.row == 0) {
            if (![cell.contentView.subviews containsObject:_loginView]){
                [cell.contentView addSubview:_loginView];
            }
        }
        if (indexPath.row == 1) {
            //工会ID
            [cell addSubview:GonghuiText];
            GonghuiText.text = self.gonghuiID;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 2) {
        XLHostApplyButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLHostApplyButtonCell class])];
        if (cell == nil) {
            cell = [[XLHostApplyButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:NSStringFromClass([XLHostApplyButtonCell class])];
            cell.contentView.backgroundColor = XLThemeColor;
            cell.backgroundColor = XLThemeColor;
        }
        cell.delagate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return ScreenWidth/2 + 30;
        }
        return ScreenWidth/3 + 70;
    }
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            return 140;
        }else{
            return 45;
        }
    }
    return 96;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 1) {
        return 10;
    }
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}

#pragma mark -- topCellDelagate
-(void)uploadHeaderAndCover:(UIButton *)button butonTag:(NSInteger)buttontag label1:(UILabel *)label1 label2:(UILabel *)label2{
    [self.loginView.phoneField resignFirstResponder];
    [self.loginView.codeField resignFirstResponder];
    [GonghuiText resignFirstResponder];
    if(buttontag == 101){//传视频
        VideoRecordViewController * recordVC  = [[VideoRecordViewController alloc] init];
        [self.navigationController pushViewController:recordVC animated:YES];
//        SHShortVideoViewController *vc = [[SHShortVideoViewController alloc]init];
//        vc.maxSeconds = 10;
//        vc.finishBlock = ^(id content) {
//            if ([content isKindOfClass:[NSString class]]) {
//                self.videoUrl = content;
//            } else if ([content isKindOfClass:[UIImage class]]){
//                UIImage *loadPathStr = content;
//                _videolabel.hidden = YES;
//                [_videoImageButton setBackgroundImage:loadPathStr forState:UIControlStateNormal];
//            }
//        };
//        [self presentViewController:vc animated:YES completion:nil];
 } else {
        //传图片
        [self updateImage:button butonTag:buttontag label1:label1 label2:label2];
    }
}

- (void)updateImage:(UIButton *)button butonTag:(NSInteger)buttontag label1:(UILabel *)label1 label2:(UILabel *)label2{
    [[BMHPhotoPickManager shareInstance] pickFromCustomViewInController:self allowEditing:YES successHandler:^(UIImage *image) {
        button.userInteractionEnabled = NO;
        [self.navigationItem.rightBarButtonItem setEnabled:NO];
        [XLHTTPSessionManager upLoadImageFileWithImage:image Progress:^(NSNumber *progress) {
            BMHLog(@"%@", progress);
             [SVProgressHUD showProgress:progress.floatValue status:@"上传中..."];
             [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
        } Success:^(id success) {
            if (buttontag == 100) {
                self.imageUrl = success;
                label1.hidden = YES;
            }if (buttontag == 200) {
                self.IDCardUrl1 = success;
            }
            if (buttontag == 201) {
                self.IDCardUrl2 = success;
            }
            [XLDownloadImageTool downloadImage:success place:nil button:button];
            button.userInteractionEnabled = YES;
            [self.navigationItem.rightBarButtonItem setEnabled:YES];
            [SVProgressHUD dismiss];
        } Failure:^(id error) {
            button.userInteractionEnabled = YES;
            [self.navigationItem.rightBarButtonItem setEnabled:YES];
            [SVProgressHUD dismiss];
        }];
        
    } cancelHandler:^{
        
    }];
}

- (void)bindingData {
    self.loginView.codeBtn.rac_command = self.viewModel.queryCodeCommand;
    self.loginView.loginButton.rac_command = self.viewModel.loginCommand;
    [self.loginView.codeBtn.rac_command.enabled subscribeNext:^(id x) {
        NSLog(@"codeBtn.enabled = %@", x);
    }];
    
    @weakify(self);
    [self.loginView.phoneField.rac_textSignal subscribeNext:^(NSString *text) {
        @strongify(self);
        if (text.length >= 11) {
            self.loginView.phoneField.text = [text substringWithRange:NSMakeRange(0, 11)];
            if ([[IQKeyboardManager sharedManager] canGoNext]) {
                [[IQKeyboardManager sharedManager] goNext];
            }
        }
        self.viewModel.phone = self.loginView.phoneField.text;
    }];
    
    [self.loginView.codeField.rac_textSignal subscribeNext:^(NSString *text) {
        @strongify(self);
        if (text.length > 6) {
            self.loginView.codeField.text = [text substringWithRange:NSMakeRange(0, 6)];
        }
        self.viewModel.code = self.loginView.codeField.text;
    }];
    
    [self.viewModel.intervalTimeSignal subscribeNext:^(id x) {
        @strongify(self);
        NSInteger intervalTime = [x integerValue];
        if (intervalTime > 0) {
            [self.loginView.codeBtn setTitle:F(@"%zds后重发", intervalTime) forState:UIControlStateNormal];
        }else{
            [self.loginView.codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
    }];
    //监听获取验证码逻辑结果
    [[RACObserve(self.viewModel, queryCodeStatus) skip:1] subscribeNext:^(id x) {
        @strongify(self);
        NSInteger statueValue = [x integerValue];
        switch (statueValue) {
            case XLLLoginViewModelStatus_Doing:{
                //                [MBProgressHUD showMessage:@"正在获取验证码..." toView:self.view];
            }
                break;
            case XLLLoginViewModelStatus_Success:{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [MBProgressHUD showContent:@"验证码已发送到您的手机" toView:self.view];
            }
                break;
            case XLLLoginViewModelStatus_Fail:{
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                NSString *errorText = self.viewModel.queryCodeError.userInfo[NSLocalizedDescriptionKey];
                errorText = errorText.length > 0 ? errorText : @"获取验证码失败";
                [MBProgressHUD showContent:errorText toView:self.view];
            }
                break;
            default:
                break;
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
